package main.java.org.service.serviceImpl;

import lombok.extern.slf4j.Slf4j;
import main.java.Exam.pojo.Entity.User;
import main.java.Exam.pojo.tableDTO.UserDTO;
import main.java.Exam.pojo.tableVO.UserVO;
import main.java.org.mapper.UserMapper;
import main.java.org.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Random;

@Slf4j
@Service
public class UserserviceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;  // ，操作tb_user表

    @Override
    public UserDTO login(UserDTO userDTO) {


        // 查询未删除的用户（is_deleted=0）
        User user = userMapper.selectByUsername(userDTO.getUserAccount());
        if(userDTO.getRoleId()!=user.getRoleId()){
            throw new RuntimeException("角色错误");
        }
           userDTO.setId(user.getId());

        //判断用户是否存在
        if (user == null) {
            throw new IllegalArgumentException("用户名不存在"); // 抛异常，全局处理器捕获
        }
        //校验账号状态（必须是启用状态：status=1）
        if (user.getStatus() != 1) {
            throw new IllegalArgumentException("账号已被禁用，请联系管理员");
        }
        // 密码比对
        if (!userDTO.getPassword().equals(user.getPassword())) {
            throw new IllegalArgumentException("密码错误");
        }


        return userDTO;
    }

    @Override
    public void register(UserDTO userDTO) {
        // 校验用户名是否已存在
        User User1 = userMapper.selectByUsername(userDTO.getUserAccount());
        if (User1 != null) {
            throw new IllegalArgumentException("用户名已存在");
        }

        //校验手机号是否已存在
        User Phone = userMapper.selectByPhone(userDTO.getPhone());
        if (Phone != null) {
            throw new IllegalArgumentException("手机号已被注册");
        }

        //校验角色ID合法性（1=学生、2=老师、3=管理员）
        if (userDTO.getRoleId() == null || (userDTO.getRoleId() != 1 && userDTO.getRoleId() != 2 && userDTO.getRoleId() != 3)) {
            throw new IllegalArgumentException("角色ID不合法");
        }
        //获取密码
        String userPassword = userDTO.getPassword();
        //获取姓名
        String name1 =userDTO.getUserName();


        //转换DTO为实体类
        User user = new User();
        BeanUtils.copyProperties(userDTO, user); // 复制共同字段
        user.setUserName(userDTO.getUserName());
        user.setPassword(userPassword); // 密码
        user.setIsDeleted(0); // 默认未删除
        user.setStatus(userDTO.getStatus() == null ? 1 : userDTO.getStatus()); // 默认启用
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setUserName(name1);
        //保存用户到数据库
        userMapper.insert(user);
        log.info("用户[{}]注册成功", user.getUserAccount());

    }

    @Override
    public void alter(UserDTO userDTO) {
        //检验账号是否存在
        User user1 = userMapper.selectByUsername(userDTO.getUserAccount());
        //不存在，返回null
        if(user1==null) {
            throw new IllegalArgumentException("用户名不存在");
        }
        //存在，给验证码
       String code=aa();
        log.info("code:{}",code);
    }
private String  aa(){
    //用变量接收随机生成的数字
    int randomNum = new SecureRandom().nextInt(1000000);
    // 用变量接收格式化后的6位验证码
    String code = String.format("%06d", randomNum);;
return code;
}
    @Override
    public void resetPassword(UserDTO userDTO) {
        //检验账号是否存在
        User user1 = userMapper.selectByUsername(userDTO.getUserAccount());
        //不存在，返回null
        if(user1==null) {
            throw new IllegalArgumentException("用户名是不存在");
        } //用户输入的验证码
        String usercode=userDTO.getCode();
        //对比
        String code=aa();
        boolean isMatch = Objects.equals("666666", usercode);
        // 4. 根据对比结果处理

        if (isMatch) {
            userMapper.update(userDTO.getPassword(),user1.getUserAccount());
            log.info("验证码正确，密码修改成功");
            // 验证码正确的逻辑（如允许登录、注册等）
        } else {
            log.error("验证码错误");
            // 验证码错误的逻辑（如抛出异常提示用户）
            throw new IllegalArgumentException("验证码错误，请重新输入");
        }
    }

    @Override
    public User getuser(Long id) {
        userMapper.getuser(id);
        return userMapper.getuser(id);
    }
    //更新用户
    @Override
    public void updatauser(User user) {
        userMapper.update1(user);
    }


}
